// 基础路径
const BASE_API = 'http://localhost:9999';

// 初始化图表
let chartOne = echarts.init(document.getElementById('main_one'));

// 加载动画
chartOne.showLoading();

// 获取工作台数据
function fetchDashboardData() {
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'login.html';
        return;
    }

    $.ajax({
        url: `${BASE_API}/dashboard/data`,
        type: 'GET',
        headers: {
            'token': token
        },
        success: function(result) {
            if (result.code === 200) {
                renderChartOne(result.data.last7DaysSales);
            } else if (result.code === -2) {
                window.location.href = 'login.html';
            } else {
                toastr.error(result.msg || '获取数据失败');
            }
        },
        error: function() {
            toastr.error('获取数据失败，请检查网络连接');
        }
    });
}

// 渲染近7天销售额趋势图
function renderChartOne(salesData) {
    const dates = salesData.map(item => item.date);
    const amounts = salesData.map(item => item.amount);

    const option = {
        title: {
            text: '近7天销售额趋势',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                return `${params[0].name}<br/>
                        销售额：￥${params[0].value.toFixed(2)}`;
            }
        },
        xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
                rotate: 30
            }
        },
        yAxis: {
            type: 'value',
            name: '销售额（元）',
            axisLabel: {
                formatter: function(value) {
                    return '￥' + value.toFixed(2);
                }
            }
        },
        series: [{
            name: '销售额',
            type: 'line',
            data: amounts,
            smooth: true,
            lineStyle: {
                width: 3
            },
            itemStyle: {
                color: '#409EFF'
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(64,158,255,0.3)'
                }, {
                    offset: 1,
                    color: 'rgba(64,158,255,0.1)'
                }])
            }
        }]
    };

    chartOne.hideLoading();
    chartOne.setOption(option);
}

// 监听窗口大小变化
window.addEventListener('resize', function() {
    chartOne.resize();
});

// 初始加载数据
fetchDashboardData();
